package org.jkuang.qstar.commons.source;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class SourceReader {

	static File tempDirectory;

	public static synchronized File getTemporaryDirectory() {
		if (tempDirectory == null) {
			tempDirectory = createTemporaryDirectory();
		}
		return tempDirectory;
	}

	public static void main(String[] args) throws IOException {
		extractResource("mysql.properties");
		extractResource("schema", "news_cms.xml");
		extractResource("schema", "report_pc.xml");
	}

	public static void extractResource(String dir, String fileName) throws IOException {
		final String resourceName = dir + '/' + fileName;
		final InputStream resource = SourceReader.class.getClassLoader().getResourceAsStream(resourceName);
		if (resource == null) {
			throw new FileNotFoundException(resourceName);
		}
		extractResource(resource, fileName, getTemporaryDirectory().toString());
	}

	public static void extractResource(String fileName) throws IOException {
		final String resourceName = fileName;
		final InputStream resource = SourceReader.class.getClassLoader().getResourceAsStream(resourceName);
		if (resource == null) {
			throw new FileNotFoundException(resourceName);
		}
		extractResource(resource, fileName, getTemporaryDirectory().toString());
	}

	private static String extractResource(InputStream resource, String resourceName, String extractToDirectory)
			throws IOException {
		final File dst = new File(extractToDirectory, resourceName);
		dst.deleteOnExit();
		final String dstPath = dst.toString();
		final long nbytes = copy(resource, dst);
		System.out.println("copy file to " + dst);
		log(String.format("copied %d bytes to %s", nbytes, dstPath));
		return dstPath;
	}

	private static void log(String msg) {
		System.err.println("index.builder.xml: " + msg);
	}

	private static long copy(InputStream src, File dstFile) throws IOException {
		FileOutputStream dst = new FileOutputStream(dstFile);
		try {
			byte[] buffer = new byte[1 << 20]; // 1MB
			long ret = 0;
			int n = 0;
			while ((n = src.read(buffer)) >= 0) {
				dst.write(buffer, 0, n);
				ret += n;
			}
			return ret;
		} finally {
			dst.close();
			src.close();
		}
	}

	private static File createTemporaryDirectory() {
		File baseDirectory = new File(System.getProperty("java.io.tmpdir"));
		String directoryName = "index_builder_xmls-" + System.currentTimeMillis() + "-";
		for (int attempt = 0; attempt < 1000; attempt++) {
			File temporaryDirectory = new File(baseDirectory, directoryName + attempt);
			if (temporaryDirectory.mkdir()) {
				return temporaryDirectory;
			}
		}
		throw new IllegalStateException(
				"Could not create a temporary directory (tried to make " + directoryName + "*)");
	}

	private SourceReader() {
	}
}
